<script lang="ts">
export default {
  name: 'manage',
};
</script>

<script lang="ts" setup>

import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';

import OperateMethodEditDialog from './components/OperateMethodEditDialog.vue';
import OperateMethodEntityTable from './components/OperateMethodEntityTable.vue';
import OperateMethodFormHeader from './components/OperateMethodFormHeader.vue';

import {getEntity,} from '@/utils/entity';

import {
  DeviceOperateQueryParam,
  RepoCompEntity,
} from '@/api/repo/comp/local/types';
import {
  queryCompEntity,
  createDeviceTemplateEntity,
  deleteDeviceTemplateEntity,
  updateDeviceTemplateEntity,
} from "@/api/repo/comp/local";
import {isNull} from "@/utils/fieldutil";

const operateMethodEditDialogRef = ref<any>(); // 这了的变量名称必须和<deviceOperate-edit-dialog>的ref值一样
const operateMethodEntityTableRef = ref<any>(); // 这了的变量名称必须和<deviceOperate-edit-dialog>的ref值一样
const operateMethodFormHeaderRef = ref<any>(); // 这了的变量名称必须和<deviceOperate-edit-dialog>的ref值一样

const dataState = reactive({
  // 组件ID
  compId: 0,
  entity: {} as RepoCompEntity,
  // 查询参数
  queryParams: {pageNum: 1, pageSize: 10} as DeviceOperateQueryParam,
  // 对话框状态
  editDialog: {
    visible: false,
  },
});

function handleCreateDialog(source: string, type: any) {
  if (source === 'header' && type === 'create') {
    let entityList = operateMethodEntityTableRef.value.getEntities();
    if (!isNull(entityList) && entityList.length > 0) {
      return;
    }

    dataState.editDialog.visible = true;
    operateMethodEditDialogRef.value.initEditData(type, dataState.entity);
    return;
  }
}

/**
 * 捕获按钮的打开对话框操作：create/update
 * @taskParam source
 * @taskParam type
 * @taskParam value
 */
function handleUpdateDialog(source: string, type: any, value: any) {
  // 更新对话框
  if (source === 'header' && type === 'update') {
    let ids = operateMethodEntityTableRef.value.getIds();
    if (ids === undefined || ids.length === 0) {
      return;
    }

    // 取出选中的元素
    let entity = getEntity(operateMethodEntityTableRef.value.getEntities(), ids[0]);
    entity.compId = dataState.entity.id;
    // 初始化编辑对话框的数据
    operateMethodEditDialogRef.value.initEditData(type, entity);
    // 显示对话框
    dataState.editDialog.visible = true;

    return;
  }

  if (source === 'table' && type === 'update') {
    if (value === undefined) {
      return;
    }

    // 取出选中的元素
    let entity = getEntity(operateMethodEntityTableRef.value.getEntities(), value);
    // 初始化编辑对话框的数据
    operateMethodEditDialogRef.value.initEditData(type, entity);
    entity.compId = dataState.entity.id;
    // 显示对话框
    dataState.editDialog.visible = true;
  }
}

function handleCreate(value: any) {
  let formData = {
    id: value.id,
    compId: value.compId,
    manufacturer: value.manufacturer,
    deviceType: value.deviceType,
    subsetName: value.subsetName,
    templateType: value.templateType,
    templateName: value.templateName,
    templateParam: value.templateParam,
    extendParam: value.extendParam,
  };


  createDeviceTemplateEntity(formData).then(() => {
    ElMessage.success('新增成功');
    // 隐藏对话框
    dataState.editDialog.visible = false;
    // 刷新表单
    operateMethodEntityTableRef.value.refreshTable(dataState.queryParams);
  })
}

function handleUpdate(value: any) {
  let formData = {
    id: value.id,
    compId: value.compId,
    manufacturer: value.manufacturer,
    deviceType: value.deviceType,
    subsetName: value.subsetName,
    templateType: value.templateType,
    templateName: value.templateName,
    templateParam: value.templateParam,
    extendParam: value.extendParam,
  }

  formData.compId = dataState.compId;
  updateDeviceTemplateEntity(formData).then(() => {
    ElMessage.success('更新成功');
    // 隐藏对话框
    dataState.editDialog.visible = false;
    // 刷新表单
    operateMethodEntityTableRef.value.refreshTable(dataState.queryParams);
  })
}

/**
 * 捕获对话框的取消操作
 * @taskParam value
 */
function handleCancel() {
  // 隐藏对话框
  dataState.editDialog.visible = false;
}


function handleQuery(source: string, value: any) {
  dataState.queryParams = value;
  operateMethodEntityTableRef.value.refreshTable(dataState.queryParams);
}

/**
 * 捕获删除对话框消息
 * @taskParam source 发出消息的数据来源：button/table
 * @taskParam type 操作类型：delete
 * @taskParam row 行信息
 */
function handleDeleteDialog(source: string, type: string, row: any) {
  let ids = '';
  if (source === 'table') {
    ids = row;
  }
  if (source === 'header') {
    let idList = operateMethodEntityTableRef.value.getIds();
    if (idList.length === 0) {
      return;
    }

    ids = idList.join(',');
  }

  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteDeviceTemplateEntity(ids).then(() => {
      ElMessage.success('删除成功');
      // 刷新表单
      operateMethodEntityTableRef.value.refreshTable(dataState.queryParams);
    });
  })
    .catch(() => ElMessage.info('已取消删除'));
}

function getUuidFromHref() {
  let tag = "/repo-comp/local/dev-template/device-list?compId=";
  let start = location.href.indexOf(tag);
  if (start <= 0) {
    return;
  }

  dataState.compId = Number.parseInt(location.href.substring(start + tag.length));
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  getUuidFromHref();

  // 查询页面对应的组件实体
  queryCompEntity(dataState.compId).then(({data}) => {
    dataState.entity = data;
  });
});

</script>

<template>
  <div class="app-container">
    <!-- 表单头：各种按钮 -->
    <operate-method-form-header ref="operateMethodFormHeaderRef"
                                @create="handleCreateDialog"
                                @query="handleQuery"
    />

    <!-- 数据表单：创建/修改 -->
    <operate-method-entity-table ref="operateMethodEntityTableRef"
                                 @delete="handleDeleteDialog"
                                 @update="handleUpdateDialog"

    />

    <!-- 设备编辑对话框：创建/修改 -->
    <operate-method-edit-dialog ref="operateMethodEditDialogRef" v-model:visible="dataState.editDialog.visible"
                                @cancel="handleCancel"
                                @create="handleCreate"
                                @update="handleUpdate"

    />

  </div>
</template>
